package com.gxc.controller;

import com.github.pagehelper.PageInfo;
import com.gxc.dao.jpa.ItemSkuRepository;
import com.gxc.dao.mapper.GoodsItemPageMapper;
import com.gxc.dto.SearchItemPlatResultDto;
import com.gxc.entity.ItemSku;
import com.gxc.utils.RestControllerResult;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 商品信息.
 *
 * @author 宫新程
 * @since 2018/12/4 10:21 AM
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

  @Resource GoodsItemPageMapper goodsItemPageMapper;
  @Resource ItemSkuRepository itemSkuRepository;

  /** 分页查询商品信息. */
  @RequestMapping("/list")
  @ResponseBody
  public PageInfo<SearchItemPlatResultDto> goodsList(
      @RequestParam(defaultValue = "1") Integer page,
      @RequestParam(defaultValue = "10") Integer size) {
    List<SearchItemPlatResultDto> data = goodsItemPageMapper.searchItemPlat(page, size);
    return new PageInfo<>(data);
  }

  /** jpa 分页查询. */
  @RequestMapping("/jpa")
  @ResponseBody
  public Page<ItemSku> findAll(
      @RequestParam(defaultValue = "1") Integer page,
      @RequestParam(defaultValue = "10") Integer size) {
    Pageable pageable = PageRequest.of(page - 1, size);
    return itemSkuRepository.findAll(pageable);
  }

  /** 保存. */
  @RequestMapping("/save")
  @ResponseBody
  public RestControllerResult<ItemSku> save() {
    ItemSku itemSku = new ItemSku();
    itemSku.setBarCode("sadada");
    itemSku.setItemId(1);
    itemSku.setItemModel("SDJHFA");
    itemSku.setMemberId(24);
    itemSku.setProductCode("SFSGSDG");
    itemSku.setType(6);
    ItemSku data = itemSkuRepository.save(itemSku);
    RestControllerResult<ItemSku> result = new RestControllerResult<>();
    result.setSuccess(true);
    result.setData(data);
    return result;
  }

  /** 用来测试全局异常处理. */
  @RequestMapping("/goods/e/{num}")
  @ResponseBody
  public RestControllerResult<Integer> testException(@PathVariable Integer num) {
    int i = 10 / num;
    RestControllerResult<Integer> result = new RestControllerResult<>();
    result.setSuccess(true);
    result.setData(i);
    return result;
  }
}

